<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="60%" v-loading="loading">
    <el-form :model="form" class="viewOrExamine" ref="form" label-width="110px">
      <el-form-item label="保单号" required>
        <el-input v-model="form.insureNum" placeholder="请输入保单号"></el-input>
      </el-form-item>
      <el-form-item label="上传保单">
        <el-upload :headers="headers" :file-list="fileList" :auto-upload="true" action="/file/upload" :http-request="uploadFile" :before-upload="beforeUpload" :on-remove="onRemove" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="returnPolicy">确定</el-button>
      <el-button @click="handleClose">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      fileList: [],
      headers: { "Content-Type": "multipart/form-data" },
      title: "回传保单",
      dialogFormVisible: false,
      form: {
        insureNum: "",
      },
      row: {},
      file: null,
    };
  },
  methods: {
    onRemove(file) {
      this.fileList = this.fileList.filter((item) => item.name !== file.name);
    },
    handleClose() {
      this.dialogFormVisible = false;
    },
    beforeUpload(file) {
      this.file = file;
      if (file.type !== "application/pdf") {
        this.$message.warning("请上传pdf");
        return false;
      }
      return true;
    },
    uploadFile() {
      this.loading = true;
      const headers = {
        "Content-Type": "multipart/form-data",
      };
      const formData = new FormData();
      formData.append("file", this.file);
      this.$post("/file/upload", formData, headers)
        .then((res) => {
          this.fileList = [
            {
              name: res.data.substring(res.data.lastIndexOf("/") + 1),
              url: res.data,
            },
          ];
        })
        .catch(() => {
          this.fileList = [];
        })
        .finally(() => {
          this.loading = false;
        });
    },
    returnPolicy() {
      if (!this.form.insureNum) {
        this.$message.error("请填写保单号");
        return;
      }
      if (this.loading) {
        return;
      }
      this.loading = true;
      const params = {
        warrantyId: this.row.warrantyId,
        insureUrl: this.fileList.length ? this.fileList[0].url : "",
        insureNum: this.form.insureNum,
      };
      this.$post(`/warranty/insure/upInfo`, params)
        .then((res) => {
          this.$message.success("回传成功"); // 成功提示信息
          this.dialogFormVisible = false;
          this.$emit("initTable");
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>
<style scoped lang="scss"></style>